# coding=utf-8
"""
作者：dnscmd@qq.com
创建时间：2025/1/19
描述：百家号爬虫
"""
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def get_text(driver, class_name="EaCvy",self_data=None):
    """
    获取页面class_name中的文本
    :param driver: chromedriver
    :param class_name: 类名
    """
    try:
        new_content_locator = (By.CLASS_NAME, class_name)  # 替换为新内容的实际 ID 或其他定位方式
        wait.until(EC.presence_of_element_located(new_content_locator))

        if not self_data:
            new_content = driver.find_element(*new_content_locator)
        else:
            new_content = driver.find_elements(By.CSS_SELECTOR, self_data)[0]
        return new_content.text
    except Exception as e:
        print(e)
        return ""



def switch_to_new_tab(driver):
    """
    切换到新标签页
    :param driver: chromedriver
    """
    wait.until(lambda d: len(d.window_handles) > 1)  # 等待新标签页出现
    driver.switch_to.window(driver.window_handles[-1])  # 切换到新标签页

def switch_to_original_tab(driver):
    """
    切换到原标签页
    :param driver: chromedriver
    """
    driver.close()
    driver.switch_to.window(driver.window_handles[0])  # 切换到原标签页

if __name__ == '__main__':


    # 配置 Chrome 浏览器
    chrome_options = Options()
    # chrome_options.add_argument('--headless')  # 无界面模式
    chrome_options.add_argument('--disable-gpu')  # 禁用 GPU 加速
    chrome_options.add_argument('--no-sandbox')  # 防止某些沙盒问题

    # ChromeDriver 路径
    chromedriver_path = r'D:\dns\tools\chrome\chromedriver.exe'  # 修改为实际路径
    service = Service(chromedriver_path)

    # 启动浏览器
    driver = webdriver.Chrome(service=service, options=chrome_options)

    try:
        # 打开目标网址
        url = "https://author.baidu.com/home?from=bjh_article&app_id=1570168240515616"
        driver.get(url)
        # 等待按钮加载
        class_name = "s-card-body"
        wait = WebDriverWait(driver, 10)
        wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, class_name)))
        buttons = driver.find_elements(By.CLASS_NAME, class_name)

        for v in buttons:
            v.click()

            print(driver.current_url)

            switch_to_new_tab(driver)
            content = get_text(driver, class_name="EaCvy")
            print(content)

            switch_to_original_tab(driver)

    except Exception as e:
        print(e)
    finally:
        # 关闭浏览器
        driver.quit()
